package com.hitgo.soccer.database;

import java.io.IOException;
import java.io.Reader;

import com.hitgo.soccer.config.ServerConfig;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class DBManager 
{
	private static int m_nModule = 10;			
	private static int m_nDefaultIndex = 0;
	private static SqlMapClient m_SQLMappers[];
	private static SqlMapClient m_ppSQLMappers[];

	private static SqlMapClient[] InitSQLMappers(int nModules, String strConfigPrex)
	{
		SqlMapClient[] SqlMapClients = new SqlMapClient[nModules];
		for(int nIndex = 0; nIndex < nModules; nIndex++)
		{
			try 
			{
				Reader reader = Resources.getResourceAsReader(strConfigPrex + (nIndex + 1) + ".xml");
				SqlMapClients[nIndex] = SqlMapClientBuilder.buildSqlMapClient(reader);
				reader.close(); 
			} 
			catch (IOException e) 
			{
				throw new RuntimeException("Something bad happened while building the SqlMapClient instance." + e, e);
			}
		}
		return SqlMapClients;
	}
	
	public static void init()
	{
		m_nModule = ServerConfig.nDBCount;
		String strPrefix = ServerConfig.strDBConfigPath + "/SqlMapConfig";
		m_SQLMappers = InitSQLMappers(m_nModule, strPrefix);
	}

	public static SqlMapClient GetSQLMapper(long lUserID)
	{
		return m_SQLMappers[(int) (lUserID % m_nModule)];
	}
	
	public static SqlMapClient GetSQLMapper(String strUserID)
	{
		if(strUserID == null || strUserID == "")
			return m_SQLMappers[m_nDefaultIndex];
		
		long lUserID = Long.parseLong(strUserID);
		
		return GetSQLMapper(lUserID);
	}
	
	public static SqlMapClient[] GetSQLMappers()
	{
		return m_SQLMappers;
	}
}
